/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.util;

import lombok.Getter;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.jrose.core.runtime.CurrentRuntimeLevel;
import org.jrose.core.runtime.RuntimeLevel;
import org.jrose.entity.data.User;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;

/**
 * User password data structure.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-23 17:29
 */
public class UserPassword implements Serializable {
    private static final long serialVersionUID = 1585094620760193400L;

    public static final String DEFAULT_PASSWORD = "123456";

    @Getter private final String plainPassword;
    @Getter private final String password;
    @Getter private final String salt;

    @JsonCreator
    public UserPassword(@JsonProperty("plainPassword") String plainPassword,
                        @JsonProperty("password") String password,
                        @JsonProperty("salt") String salt) {
        this.plainPassword = plainPassword;
        this.password = password;
        this.salt = salt;
    }

    public boolean match(String plain) {
        if (plain == null) {
            return false;
        }
        String encode = obscurePassword(plain, salt);
        return StringUtils.equals(encode, password);
    }

    public void attach(User user) {
        if (user == null) {
            return;
        }
        user.setPlainPassword(plainPassword);
        user.setPassword(password);
        user.setSalt(salt);
    }

    // static factory methods:

    public static UserPassword newInstance(User user) {
        if (user == null) {
            return null;
        }
        return new UserPassword(user.getPlainPassword(), user.getPassword(), user.getSalt());
    }

    public static UserPassword newInstance() {
        if (CurrentRuntimeLevel.le(RuntimeLevel.TEST)) {
            return newInstance(DEFAULT_PASSWORD);
        }
        return newInstance(RandomUtils.randomNumeric(6));
    }

    public static UserPassword newInstance(String plainPassword) {
        Validate.notNull(plainPassword, "Plain password must not be null");
        Validate.isTrue(plainPassword.length() >= 1 && plainPassword.length() <= 16, "Illegal plain password length");

        String salt = RandomUtils.randomAlphabetNumeric(6);
        String password = UserPassword.obscurePassword(plainPassword, salt);
        return new UserPassword(plainPassword, password, salt);
    }

    // private methods:

    private static String obscurePassword(String password, String salt) {
        Validate.notNull(password);
        Validate.notNull(salt);

        StringBuilder sbuf = new StringBuilder();
        sbuf.append("#(").append(password).append(salt).append(")#");
        try {
            return DigestUtils.sha1Hex(sbuf.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }
}
